package com.draven.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.draven.common.core.domain.AjaxResult;
import com.draven.common.core.BasePageQuery;
import com.draven.common.entity.Note;
import com.draven.common.entity.NoteCategory;
import com.draven.common.entity.NoteTag;
import com.draven.system.service.INoteCategoryService;
import com.draven.system.service.INoteService;
import com.draven.system.service.INoteTagService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 笔记Controller
 * 
 * @author draven
 */
@Controller
@RequestMapping("/note")
public class NoteController {
    
    private static final Logger logger = LoggerFactory.getLogger(NoteController.class);

    private String prefix = "note";

    @Autowired
    private INoteService noteService;

    @Autowired
    private INoteCategoryService noteCategoryService;

    @Autowired
    private INoteTagService noteTagService;

    @GetMapping()
    public String note() {
        return prefix + "/note";
    }

    /**
     * 查询笔记列表
     */
    @PostMapping("/list")
    @ResponseBody
    public AjaxResult list(Note note, BasePageQuery pageQuery) {
        IPage<Note> list = noteService.selectNotePageList(note, pageQuery);
        return AjaxResult.success(list);
    }

    /**
     * 根据标签查询笔记列表
     */
    @GetMapping("/listByTag/{tagId}")
    @ResponseBody
    public AjaxResult listByTag(@PathVariable("tagId") Long tagId, BasePageQuery pageQuery) {
        IPage<Note> list = noteService.selectNotesByTagId(tagId, pageQuery);
        return AjaxResult.success(list);
    }

    /**
     * 查询最近笔记
     */
    @GetMapping("/recent")
    @ResponseBody
    public AjaxResult recent(@RequestParam(defaultValue = "10") Integer limit) {
        List<Note> list = noteService.selectRecentNotes(limit);
        return AjaxResult.success(list);
    }

    /**
     * 查询热门笔记
     */
    @GetMapping("/hot")
    @ResponseBody
    public AjaxResult hot(@RequestParam(defaultValue = "10") Integer limit) {
        List<Note> list = noteService.selectHotNotes(limit);
        return AjaxResult.success(list);
    }

    /**
     * 新增笔记
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        // 获取分类列表
        List<NoteCategory> categories = noteCategoryService.selectCategoryList(new NoteCategory());
        // 获取标签列表
        List<NoteTag> tags = noteTagService.selectTagList(new NoteTag());
        mmap.put("categories", categories);
        mmap.put("tags", tags);
        return prefix + "/add";
    }

    /**
     * 新增保存笔记
     */
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated @RequestBody Note note) {
        return AjaxResult.success(noteService.insertNote(note));
    }

    /**
     * 修改笔记
     */
    @GetMapping("/edit/{noteId}")
    public String edit(@PathVariable("noteId") Long noteId, ModelMap mmap) {
        Note note = noteService.selectNoteById(noteId);
        // 获取分类列表
        List<NoteCategory> categories = noteCategoryService.selectCategoryList(new NoteCategory());
        // 获取标签列表
        List<NoteTag> tags = noteTagService.selectTagList(new NoteTag());
        mmap.put("note", note);
        mmap.put("categories", categories);
        mmap.put("tags", tags);
        return prefix + "/edit";
    }

    /**
     * 修改保存笔记
     */
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated @RequestBody Note note) {
        return AjaxResult.success(noteService.updateNote(note));
    }

    /**
     * 删除笔记
     */
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return AjaxResult.success(noteService.deleteNoteByIds(convertToLongArray(ids)));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 笔记详情
     */
    @GetMapping("/detail/{noteId}")
    public String detail(@PathVariable("noteId") Long noteId, ModelMap mmap) {
        try {
            Note note = noteService.selectNoteById(noteId);
            // 增加浏览量
            if (note != null) {
                noteService.incrementViewCount(noteId);
                mmap.put("note", note);
            }
        } catch (Exception e) {
            // 记录异常日志
            logger.error("获取笔记详情失败，noteId: " + noteId, e);
        }
        return prefix + "/detail";
    }

    /**
     * 获取笔记详情（API）
     */
    @GetMapping("/info/{noteId}")
    @ResponseBody
    public AjaxResult info(@PathVariable("noteId") Long noteId) {
        Note note = noteService.selectNoteById(noteId);
        return AjaxResult.success(note);
    }

    /**
     * 点赞笔记
     */
    @PostMapping("/like/{noteId}")
    @ResponseBody
    public AjaxResult like(@PathVariable("noteId") Long noteId) {
        return AjaxResult.success(noteService.incrementLikeCount(noteId));
    }

    /**
     * 设置置顶状态
     */
    @PostMapping("/top")
    @ResponseBody
    public AjaxResult updateTopStatus(@RequestParam Long noteId, @RequestParam Integer isTop) {
        return AjaxResult.success(noteService.updateTopStatus(noteId, isTop));
    }

    /**
     * 设置公开状态
     */
    @PostMapping("/public")
    @ResponseBody
    public AjaxResult updatePublicStatus(@RequestParam Long noteId, @RequestParam Integer isPublic) {
        return AjaxResult.success(noteService.updatePublicStatus(noteId, isPublic));
    }

    /**
     * 转换字符串数组为Long数组
     */
    private Long[] convertToLongArray(String str) {
        String[] arr = str.split(",");
        Long[] longArr = new Long[arr.length];
        for (int i = 0; i < arr.length; i++) {
            longArr[i] = Long.parseLong(arr[i]);
        }
        return longArr;
    }
}
